package org.wzq.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.wzq.biz.Section;
import org.wzq.biz.Topic;
import org.wzq.biz.User;
import org.wzq.dao.SectionDao;
import org.wzq.dao.TopicDao;
import org.wzq.dao.UserDao;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * project: spring-mvc-forum
 * ate: 14-9-16
 * author: wzq
 * description: TODO
 */

@Controller
@RequestMapping("/section")
public class SectionController {
    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    private UserDao userDao;

    @Autowired
    private SectionDao sectionDao;

    @Autowired
    private TopicDao topicDao;

    public void printReq(HttpServletRequest req) {
        logger.info(req.getMethod() + "  " + req.getRequestURI());
    }

    @RequestMapping(value = {"/{sectionId}/page/{currPage}"}, method = {RequestMethod.GET})
    public ModelAndView showSectionByPage(@PathVariable String sectionId, @PathVariable int currPage, HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        // TODO:
        int maxPage = topicDao.getMaxPageNum(sectionId);

        List<Topic> topicList = topicDao.getTopicBySectionIdAndPage(sectionId, currPage, maxPage);
        Section section = sectionDao.getSectionById(sectionId);
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("maxPage", maxPage);
        map.put("currPage", currPage);
        map.put("topicList", topicList);
        map.put("section", section);
        return new ModelAndView("section", "map", map);
    }

    @RequestMapping(value = "/{sectionId}/article", method = {RequestMethod.GET})
    public ModelAndView articlePage(@PathVariable String sectionId, HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        // 判断登录状态
        User user = (User) req.getSession().getAttribute("user");
        if (user == null) {
            return new ModelAndView("err_require_login");
        }
        return new ModelAndView("topic_write", "sectionId", sectionId);
    }

    @RequestMapping(value = "/{sectionId}/article", method = {RequestMethod.POST})
    @ResponseBody
    public String article(@PathVariable String sectionId, HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        // 发表文章
        User user = (User) req.getSession().getAttribute("user");
        JSONObject retJson = new JSONObject();
        if (user == null) {
            retJson.put("isSucc", "false");
            retJson.put("errMsg", "请先登录");
            return retJson.toString();
        }

        InputStream inputStream = req.getInputStream();
        String str = IOUtils.stream2String(inputStream, "utf-8");
        JSONObject json = new JSONObject(str);
        String title = json.getString("title");
        String content = json.getString("content");

        // 保存该发表
        Topic topic = new Topic(Integer.parseInt(sectionId), user.getUserId(), user.getName(), title, content);
        topicDao.saveOrUpdate(topic);

        // 对应版块 + 1
        Section section = sectionDao.getSectionById(sectionId);
        section.incTopicNum();
        sectionDao.saveOrUpdate(section);

        retJson.put("isSucc", "true");
        return retJson.toString();
    }

    @RequestMapping(value = "/{sectionId}/topic/articleReply", method = {RequestMethod.POST})
    @ResponseBody
    public String articleReply(@PathVariable String sectionId, HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        // 发表文章
        User user = (User) req.getSession().getAttribute("user");
        JSONObject retJson = new JSONObject();
        if (user == null) {
            retJson.put("isSucc", "false");
            retJson.put("errMsg", "请先登录");
            return retJson.toString();
        }

        InputStream inputStream = req.getInputStream();
        String str = IOUtils.stream2String(inputStream, "utf-8");
        System.out.println("str = " + str);
        JSONObject json = new JSONObject(str);
        String title = json.has("title") ? json.getString("title") : null;
        String content = json.getString("content");
        String pTopicId = json.getString("pTopicId");

        // 回复帖 入库
        Topic topic = new Topic(Integer.parseInt(sectionId), user.getUserId(), user.getName(), title, content);
        topic.setpTopicId(Integer.parseInt(pTopicId));
        topicDao.saveOrUpdate(topic);

        // 原帖回复+1
        Topic srcTopic = topicDao.getTopicById(pTopicId);
        srcTopic.incReplyNum();
        topicDao.saveOrUpdate(srcTopic);

        retJson.put("isSucc", "true");
        return retJson.toString();
    }

    @RequestMapping(value = "/{sectionId}/topic/{topicId}", method = {RequestMethod.GET})
    public ModelAndView showTopic(@PathVariable String sectionId, @PathVariable String topicId, HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        Topic topic = topicDao.getTopicById(topicId);
        topic.incViewNum();
        topicDao.saveOrUpdate(topic);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("topic", topic);
        map.put("sectionId", sectionId);
        map.put("replyList", topicDao.getReplyById(topicId));

        return new ModelAndView("topic", "map", map);
    }
}
